<template>
  <!-- oa系统常用表格 -->
  <!-- selection-change 当多选状态改变时触发 -->
  <div class="inductionOperation">
    <div class="induction">
      <!--新增待入职按钮-->
      <el-button class="waiting" type="primary" @click="openWaitingDialog">新增待入职</el-button>
      <my-dialog :dialogState="dialogWaiting"
                 :row="waitingForm"
                 :statusList="statusList"
                 :depts="depts"
                 :formLabelWidth="formLabelWidth"
                 :dropLabelWidth="dropLabelWidth"
                 mode="3"></my-dialog>
      <!--办理入职按钮-->
      <el-button type="primary"
                 :disabled="inductionArray.length===0"
                 @click="openInductionDialog">办理入职
      </el-button>
      <el-dialog v-model="dialogInduction" title="添加员工信息">
        <!-- 办理入职 -->
        <el-form :inline="true" :model="inductionForm">
          <div class="induction-first-item">
            <el-form-item label="入职时间" :label-width="formLabelWidth">
              <div class="block">
                <el-date-picker v-model="inductionForm.entryDate"
                                value-format="YYYY-MM-DD"
                                type="date" placeholder="入职时间">
                </el-date-picker>
              </div>
            </el-form-item>
            <el-form-item label="状态" :label-width="dropLabelWidth">
              <el-select v-model="inductionForm.status" placeholder="请选择状态">
                <el-option v-for="item in statusList" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-form>
        <!-- 表单尾部取消和确认按钮 -->
        <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogInduction = false">取消</el-button>
          <el-button type="primary" @click="handleInduction">确认</el-button>
        </span>
        </template>
      </el-dialog>
    </div>
    <my-search></my-search>
  </div>
  <div class="WaitingTable">
    <el-table class="induction-table"
              ref="multipleTableRef"
              :data="curData"
              border
              style="width: 90%; max-height: 400px;"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50"></el-table-column>
      <!--<el-table-column property="workerId" label="编号" width="80"></el-table-column>-->
      <el-table-column property="name" label="姓名" width="80"></el-table-column>
      <el-table-column property="dept" label="部门" width="130"></el-table-column>
      <el-table-column property="post" label="岗位" width="120"></el-table-column>
      <el-table-column property="phone" label="手机号码" width="125"></el-table-column>
      <el-table-column property="id" label="身份证号" width="190"></el-table-column>
      <el-table-column property="status" label="状态" width="90"></el-table-column>
      <el-table-column property="estimatedDate" label="预计入职时间" width="128"></el-table-column>
      <el-table-column fixed="right" label="操作" width="105">
        <template #default="scope">
          <el-button link type="primary"
                     size="small"
                     @click="updateEmployee(scope.row)">编辑
          </el-button>
          <el-button link @click="confirmSingleDelete(scope.row.workerId)"
                     type="primary" size="small">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <my-pagination :totalSize="totalSize"
                   :pageSize="pageSize"
                   :cur="cur"
                   :totalPage="totalPage"></my-pagination>
    <my-dialog :dialogState="dialogUpdateEmployee"
               :row="row"
               :statusList="statusList"
               :depts="depts"
               :formLabelWidth="formLabelWidth"
               :dropLabelWidth="dropLabelWidth"
               mode="2"></my-dialog>
  </div>
</template>

<script>
  import MyDialog from '@/components/dialogs/myDialog/MyDialog'
  import MyPagination from '@/components/myPagination/MyPagination'
  import MySearch from '@/components/mySearch/MySearch'
  import {myMixin} from "../../../../plugins/mixin";

  export default {
    name: "Induction",
    mixins: [myMixin],
    data() {
      return {
        row: {},
        includeDelete: [],
        dialogInduction: false,
        dialogWaiting: false,
        dialogUpdateEmployee: false,
        inductionArray: [],
        statusList: ['', '试用期', '正式员工'], // 可选状态
        formInline: {
          name: ""
        },
        inductionForm: { // 确认入职对话框表单
          entryDate: this.getNowDate(),
          status: ""
        },
        waitingForm: { // 添加待入职员工对话框表单
          name: '',
          sex: '男',
          phone: '',
          id: '',
          dept: '',
          post: '',
          status: '待入职',
          estimatedDate: this.getNowDate(),
          birth: "",
        }
      }
    },
    methods: {
      /* 处理多选框选择状态变化 */
      handleSelectionChange(arr) {
        this.inductionArray = arr;
        console.log(arr);
      },
      /* 待入职处理 */
      async handleWaiting() {
        const worker_id = parseInt(this.includeDelete[this.includeDelete.length - 1].workerId.substr(5));
        console.log(this.waitingForm);
        this.waitingForm['workerId'] = 'admin' + String(worker_id + 1);
        let str1 = this.$qs.stringify(this.waitingForm);
        await this.$request('/employee/insertwaiting?' + str1);
        await this.showWaitings();
        this.changePage(1);
        this.dialogWaiting = false;
        this.waitingForm = {
          name: '',
          sex: '男',
          phone: '',
          id: '',
          dept: '',
          post: '',
          status: '待入职',
          estimatedDate: this.getNowDate(),
          birth: '2000-01-01',
        }
      },
      /* 获取所有选中的员工编号 */
      async getInductionWorkerIds() {
        const ids = [];
        for (const item of this.inductionArray) {
          ids.push(item.workerId);
        }
        console.log(ids);
        return ids;
      },
      /* 确认入职处理 */
      async handleInduction() {
        const ids = await this.getInductionWorkerIds();
        if (ids.length > 0) {
          await this.$request('/employee/handleinduction', {
            inductions: ids,
            status: this.inductionForm.status,
            entryDate: this.inductionForm.entryDate
          });
          await this.showWaitings();
          this.changePage(this.cur);
          this.dialogInduction = false;
        }
      },
      /* 打开添加待入职对话框 */
      openWaitingDialog() {
        this.dialogWaiting = true;
      },
      /* 打开确认入职对话框 */
      openInductionDialog() {
        this.dialogInduction = true;
      },
      /* 展示所有待入职员工信息 */
      async showWaitings() {
        let result = await this.$request('/employee/list');
        this.includeDelete = result.data;
        this.tableData = [];
        for (const item of this.includeDelete) {
          if (item.visibility === '2' && item.status === "待入职") {
            this.tableData.push(item);
          }
        }
      },
      /* 切页 */
      changePage(cur) {
        this.cur = cur;
        let start = (this.cur - 1) * this.pageSize;
        let end = start + this.pageSize;
        this.curData = this.tableData.slice(start, end);
      },
      /* 编辑员工信息 */
      updateEmployee(row) {
        // console.log("click", row);
        if (row.formalDate === "" || row.formalDate == null) {
          row.formalDate = '2099-01-01'
        }
        this.dialogUpdateEmployee = true;
        this.row = row;
      },
      /* 编辑员工信息确认 */
      async confirmUpdateEmployee() {
        let str = this.$qs.stringify(this.row);
        let res = await this.$request('/employee/updateinduction?' + str);
        // console.log(res);
        await this.showWaitings();
        this.changePage(this.cur);
        this.dialogUpdateEmployee = false;
      },
      /* 单个删除（离职）确认 */
      confirmSingleDelete(workerId) {
        this.$confirm('此操作将删除信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          this.singleDelete(workerId);
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
      },
      /* 单个删除（离职） */
      async singleDelete(workerId) {
        let res = await this.$request('/employee/singlequit', {
          workerId
        });
        await this.showWaitings();
        this.changePage(this.cur);
      },
      /* 根据员工姓名搜索 */
      async search(name) {
        let result = await this.$request("/employee/searchbyname", {
          name,
          status: '待入职'
        });
        this.tableData = result.data;
        this.changePage(1);
      },
    },
    components: {
      MyDialog,
      MyPagination,
      MySearch
    },
    async mounted() {
      console.log("Induction.vuw created!");
      this.getDepts();
      await this.showWaitings();
      this.curData = this.tableData.slice(0, this.pageSize);
      // MyDialog
      this.$bus.on("confirmOperation", (mode) => {
        if (mode === '2') {
          this.confirmUpdateEmployee();
        } else if (mode === '3') {
          this.handleWaiting();
        }
      });
      this.$bus.on('changeDialogState', (mode) => {
        if (mode === '2') {
          this.dialogUpdateEmployee = false;
        } else if (mode === '3') {
          this.dialogWaiting = false;
        }
      });
      // MyPagination
      this.$bus.on("changePageNumber", (cur) => {
        this.changePage(cur);
      });
      // MySearch
      this.$bus.on("searchByName", (name) => {
        this.search(name);
      })
    }
  }
</script>

<style scoped>
  .induction {
    display: flex;
    margin-top: -1px;
  }

  .waiting {
    margin-right: 30px;
  }

  .inductionOperation {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
    margin-bottom: 8px;
    padding: 0 80px 0 30px;
  }

  .induction-table {
    margin-left: 30px;
  }

  .induction-first-item {
    margin-top: 24px;
  }
</style>